package com.lkd.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lkd.business.MsgHandler;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.service.ChannelService;
import com.lkd.service.VendingMachineService;
import com.lkd.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Topic(TopicConfig.VMS_SUPPLY_TOPIC)
public class SupplyHandler implements MsgHandler {
    @Autowired
    private ChannelService channelService;

    @Autowired
    private VendingMachineService vendingMachineService;

    @Override
    public void process(String jsonMsg) throws IOException {
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        String innerCode = supplyContract.getInnerCode();
        vendingMachineService.update(new LambdaUpdateWrapper<VendingMachineEntity>().eq(VendingMachineEntity::getInnerCode,innerCode).set(VendingMachineEntity::getLastSupplyTime,LocalDateTime.now()));
        List<SupplyChannel> supplyData = supplyContract.getSupplyData();
        for (SupplyChannel supplyDatum : supplyData) {
            ChannelEntity channelEntity = channelService.getOne(new LambdaQueryWrapper<ChannelEntity>().eq(ChannelEntity::getInnerCode, innerCode).eq(ChannelEntity::getChannelCode, supplyDatum.getChannelId()));
            channelEntity.setSkuId(supplyDatum.getSkuId());
            channelEntity.setCurrentCapacity(channelEntity.getCurrentCapacity() + supplyDatum.getCapacity());
            channelEntity.setLastSupplyTime(LocalDateTime.now());
            channelService.updateById(channelEntity);
        }
    }
}